import {Component, OnInit, ViewEncapsulation, ChangeDetectionStrategy} from '@angular/core';
import {TeacherService} from "@train/teacher/teacher.service";
import {ActivatedRoute, Params, Router} from "@angular/router";
import {AuthService} from "@shared/service/auth/auth.service";
import * as API from "@api/index";
import {ImageServeService} from "@shared/service/image/image-serve.service";
import {ToolsService} from "@shared/service/tools/tools.service";


@Component({
  selector: 'score-input',
  templateUrl: './score-input.component.html',
  styleUrls: ['./score-input.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ScoreInputComponent implements OnInit {
  public studentList = [];
  public studentInfo;
  public testInfo = {};
  public testScoreOptions = [];
  public gradeList;
  public stateStore = {
    showMenu: false
  };
  public dataStore = {
    // currentStudentAgeGroup: 0,
    testItemText: '',
    testContentText: '',
    testContentOptions: [],
    defaultAvatar: '',
    testTypeId: 0,
    saveBtnText: '保存进入下一位'
  };
  public paramStore = {
    orgUserId: '',
    classId: 0,
    studentId: 0,
    testItemId: 0,
    testContentId: 0, // 测试内容ID
    ageDictionarieId: 0,  // 年龄组ID
    // testScore: 0,  // 分数
    currentDate: ''
  };
  public checkedOptions = []; // 选中的加减分项


  constructor(private teacherService: TeacherService,
              private route: ActivatedRoute,
              private _authService: AuthService,
              private tool: ToolsService,
              public imageService: ImageServeService,
              private router: Router) {
    this.dataStore.defaultAvatar = imageService.getAvatarIcon();
    this.route.params
      .switchMap((params: Params) => {
        return this.route.queryParams;
      }).subscribe((queryParams: Params) => {
      const params = this.paramStore;
      params.classId = queryParams['classId'];
      params.studentId = +queryParams['studentId'];
      params.testItemId = queryParams['testItemId'];
      params.testContentId = queryParams['testContentId'];
      this.dataStore.testTypeId = +queryParams['testType'];
      params.orgUserId = this._authService.getAuthOrgId();
      params.currentDate = new Date().toLocaleDateString("zh-CN").replace(/\//g, '-');
    });

  }


  /**
   * @description 提交测试结果
   * @author ouyqx-691
   * @date 2018-4-11
   */
  postStudentTestScore() {
    // 处理最终结果
    const options = this.testScoreOptions;
    const testInfo = this.testInfo;
    const checkedOptions = [];
    for (let i = 0; i < options.length; i++) {
      const option = options[i];
      if (option.flag) {
        const item = {
          testMethodId: option.id,
          testScore: option.score,
          testScoreDesc: option.unit
        };
        checkedOptions.push(item);
      }
    }
    const {orgUserId, studentId, testItemId, testContentId, ageDictionarieId, currentDate} = this.paramStore;

    const formData = {
      extraTestScores: checkedOptions,
      orgUserId: orgUserId,
      studentId: studentId,
      testDate: currentDate,
      testLevelId: ageDictionarieId,
      testMethodId: testContentId,
      testModeId: testItemId,
      testScore: testInfo['testScore'],
      testScoreDesc: testInfo['unitName'],
      testScoreType: testInfo['testScoreType']
    };
    this.teacherService.postStudentTestScore(formData).subscribe((res) => {
      if (res.result === '0' && res.data) {
        this.handleNextStudent();
        this.tool.showToast('保存成功');
      }
    });
  }


  /**
   * @description 通过学生ID查询学生信息（教练）
   * @author ouyqx-691
   * @date 2018-4-16
   */
  getStudentInfoByStudentId() {
    const {studentId, orgUserId} = this.paramStore;
    const params = {
      studentId: studentId,
      orgUserId: orgUserId,
    };
    this.teacherService.getStudentInfoByStudentId(params).subscribe((res) => {
      if (res.result === '0' && res.data) {
        this.studentInfo = res.data;
        this.paramStore.ageDictionarieId = res.data.testAgeId;

        this.handleSaveBtnText();
        this.getTestItemScoreOption();
        if (this.dataStore.testTypeId === 0 && !this.gradeList) { // 主观测试项且未加载过才加载
          this.getTestScoreCriteria();
        }
      }
    });
  }

  /**
   * @description 初始化加减分选择结果
   * @author ouyqx-691
   * @date 2018-4-16
   */
  initTestItemScoreOptionResult() {
    const testScoreOptions = this.testScoreOptions;
    for (let i = 0; i < testScoreOptions.length; i++) { // 初始化加减分选项
      const item = {
        testMethodId: testScoreOptions[i].id,
        testScore: testScoreOptions[i].score,
        testScoreDesc: testScoreOptions[i].unit
      };
      this.checkedOptions.push(item);
    }
  }

  /**
   * @description 获取测试项加减分选项
   * @author ouyqx-691
   * @date 2018-4-16
   */
  getTestItemScoreOption() {
    const {studentId, testItemId, testContentId, ageDictionarieId, currentDate} = this.paramStore;
    const params = {
      studentId: studentId,
      ageDictionarieId: ageDictionarieId,
      testDateStr: currentDate,
      testMethodId: testContentId,
      testModeId: testItemId,
      sportType: '3002'
    };
    this.teacherService.getTestItemScoreOption(params).subscribe((res) => {
      if (res.result === '0' && res.data) {
        this.testInfo = res.data;
        if (res.data.scoureDetaiList) { // 存在加减分选项
          this.testScoreOptions = res.data.scoureDetaiList;
          this.initTestItemScoreOptionResult();
        }
      }
    });
  }

  /**
   * @description 通过测试内容ID获取相关文字（教练）
   * @author ouyqx-691
   * @date 2018-4-11
   */
  handleScoreOptionChange(option) {
    option.flag = !option.flag;
  }

  /**
   * @description 根据班级信息查询学员列表（录入成绩流程）
   * @author ouyqx-691
   * @date 2017-12-31
   */
  getStudentListByClassForTeacher() {
    const {orgUserId, classId, testContentId} = this.paramStore;
    const params = {
      page: 100,
      rows: 100,
      classId: classId,
      orgUserId: orgUserId,
      testItemId: testContentId
    };
    this.teacherService.getStudentListByClassForTeacher(params).subscribe((res) => {
      if (res.result === '0' && res.data.list) {
        this.studentList = res.data.list;
      }
    });
  }

  /**
   * @description 保存进入下一位（录入成绩流程）
   * @author ouyqx-691
   * @date 2017-12-31
   */
  handleNextStudent() {
    const studentList = this.studentList;
    const studentId = this.paramStore.studentId;

    for (let i = 0; i < studentList.length; i++) {
      if (studentId === studentList[i].studentId) {
        if (i < studentList.length - 1) { // 存在最后一个学生
          this.paramStore.studentId = studentList[i + 1].studentId; // 查询下一个学生信息
          this.handleSaveBtnText();
          this.getStudentInfoByStudentId();
        } else { // 已是最后一个学生，返回学生列表
          window.history.go(-1);
        }
      }
    }
  }


  /**
   * @description 处理按钮文字（录入成绩流程）
   * @author ouyqx-691
   * @date 2017-12-31
   */
  handleSaveBtnText() {
    const studentList = this.studentList;
    const studentId = this.paramStore.studentId;

    for (let i = 0; i < studentList.length; i++) {
      if (studentId === studentList[i].studentId) {
        if (i === studentList.length - 1) {
          this.dataStore.saveBtnText = '保存';
        }
      }
    }
  }

  /**
   * @description 查询评分标准（教练）
   * @author ouyqx-691
   * @date 2018-4-11
   */
  getTestScoreCriteria() {
    const {ageDictionarieId, testContentId} = this.paramStore;
    const params = {
      orgUserId: this._authService.getAuthOrgId(),
      itemId: testContentId,
      ageId: ageDictionarieId
    };
    this.teacherService.getTestScoreCriteria(params).subscribe((res) => {
      if (res.result === '0' && res.data) {
        this.gradeList = res.data.standardList;
      }
    });
  }

  /**
   * @description 处理主观测试项选择结果（教练）
   * @author ouyqx-691
   * @date 2018-4-11
   */
  handleGradeOptionChange(value) {
    Object.assign(this.testInfo, {
      testScore: value
    });
  }

  /**
   * @description 前往评分标准页面（教练）
   * @author ouyqx-691
   * @date 2018-4-11
   */
  goToScoreCriteriaPage() {
    const {ageDictionarieId, testItemId, testContentId, studentId} = this.paramStore;
    this.router.navigate([`/train/teacher/score-criteria`], {
      queryParams: {
        ageGroupId: ageDictionarieId,
        testItemId: testItemId,
        testItemText: this.testInfo['testModeName'],
        testContentId: testContentId,
        studentId: studentId,
        currentDate: this.paramStore.currentDate,
        ageGroupText: this.studentInfo.testAgeName
      }
    });
  }

  ngOnInit() {

    this.getStudentListByClassForTeacher();
    this.getStudentInfoByStudentId();
  }
}
